import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import getPageTitle from './utils/get-page-title'
import { asyncRoutes } from '@/router/index'
// import { getToken } from '@/utils/auth' // get token from cookie
// import getPageTitle from '@/utils/get-page-title'

// NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login', '/404'] // no redirect whitelist

router.beforeEach(async(to, from, next) => {
  document.title = getPageTitle(to.meta.title)
  NProgress.start()
  const token = store.state.user.token
  if (token) {
    if (to.path === '/login') {
      next('/') //  指定了跳转页面 不会经过router.beforeEach
      NProgress.done()
    } else {
      if (!store.state.user.userInfo.userId) {
        const menus = await store.dispatch('user/getUserInfo')
        const filterList = asyncRoutes.filter(route => {
          return menus.includes(route.children[0].name)
        })
        filterList.push({ path: '*', redirect: '/404', hidden: true })
        store.commit('menus/setMenu', filterList)
        router.addRoutes(filterList)
        next({ ...to, replace: true })
      } else {
        next()
      }
    }
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      Message.warning('您还未登录，请先登录')
      next('/login')
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
